package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.CIncome;
import com.example.entity.First;
import com.example.entity.Income;
import com.example.mapper.FirstMapper;
import com.example.mapper.IncomeMapper;
import com.example.service.IIncomeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 收入表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-29
 */
@Service
@RequiredArgsConstructor
public class IncomeServiceImpl extends ServiceImpl<IncomeMapper, Income> implements IIncomeService {

    private final IncomeMapper incomeMapper;

    private final FirstMapper firstMapper;

    //根据给的时间选择合适的时间尺度返回对应的数额
    @Override
    public List<Double> details(LocalDate begin, LocalDate end) {
        List<Double> amounts = new ArrayList<>();
        Long month = begin.until(end, ChronoUnit.MONTHS);
            if(month == 1){
                long days = end.toEpochDay() - begin.toEpochDay();
                for (int i = 0; i < days; i++) {
                    Double amount = incomeMapper.getAmounts1(begin);
                    begin = begin.plusDays(1);
                    amounts.add(amount);
                }
            }else{
                for (int i = 0; i < month; i++) {
                    Double amount = incomeMapper.getAmounts2(begin,begin.plusMonths(1));
                    begin = begin.plusMonths(1);
                    amounts.add(amount);
                }
            }
        return amounts;
    }

    @Override
    public List<CIncome> classified(LocalDate begin, LocalDate end) {
        List<CIncome> incomeList = new ArrayList<>();
        List<First> firsts = firstMapper.selectList(new LambdaQueryWrapper<First>()
                .eq(First::getJudge, 0));
        for (First first : firsts) {
            CIncome cIncome = new CIncome();
            cIncome.setName(first.getTypeName());
            cIncome.setValue(incomeMapper.getAmounts(begin,end,first.getId()));
            incomeList.add(cIncome);
        }
        return incomeList;
    }

    @Override
    public Double sumByTime(LocalDate begin, LocalDate end) {
        return incomeMapper.getAmounts2(begin,end);
    }
}
